//
//  BRSDatabase.m
//  Pint
//
//  Created by xiect on 13-10-30.
//  Copyright (c) 2013年 brains. All rights reserved.
//

#import "BRSDatabaseHelp.h"


@interface BRSDatabaseHelp()
- (FMDatabase*)openDatabase:(NSString*)dbFilename;
- (void)createEditableCopyOfDatabaseIfNeeded:(BOOL)force;
@end

@implementation BRSDatabaseHelp

+(BRSDatabaseHelp *)sharedDatabase{
    static BRSDatabaseHelp *sharedInstanceDB = nil;
	static dispatch_once_t onceTokenForDatabase;
	dispatch_once(&onceTokenForDatabase, ^{
		sharedInstanceDB = [[BRSDatabaseHelp alloc] init];
	});
	return sharedInstanceDB;
}

- (id)init{
    self = [super init];
    if (self) {
        _database = nil;
    }
    return self;
}

-(FMDatabase *)connect2Database{
    if(self.database == nil){
        // データベースファイルがあるの場合
        self.database = [self openDatabase:kDATABASE_NAME];
        if(self.database == nil){
            // データベースファイルがないの場合、ソースから新規する
            [self createEditableCopyOfDatabaseIfNeeded:YES];
             self.database = [self openDatabase:kDATABASE_NAME];
        }
    }
    return self.database;
}

// オペン既存のデータベースファイル
- (FMDatabase*)openDatabase:(NSString*)dbFilename{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:dbFilename];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSLog(@"path1:%@",dbPath);
    BOOL isExists = [fileManager fileExistsAtPath:dbPath];
    if (isExists) {
        FMDatabase *db = [FMDatabase databaseWithPath:dbPath] ;
        return db;
    }
    
//    if (![db open]) {
//        return nil;
//    }
	return nil;
}


// コピデータベースファイル
- (void)createEditableCopyOfDatabaseIfNeeded:(BOOL)force{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:kDATABASE_NAME];
    if (force) {
        [fileManager removeItemAtPath:writableDBPath error:&error];
    }
    
    success = [fileManager fileExistsAtPath:writableDBPath];
    
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kDATABASE_NAME_SRC];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"ソースデータベースファイル'%@'から初期化失敗!", [error localizedDescription]);
    }
}

- (void)dealloc {
    if ([_database open]) {
        [self close];
    }
}

- (void)open{
    if (![_database open]) {
        NSAssert(0, @"データベースオペン失敗!");
    }
}

- (void)close{
    if (![_database close]) {
        NSAssert(0, @"データベースクロス失敗!");
    }
}
@end
